﻿using ExamWeek01.Repository;
using ExamWeek01.Service.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExamWeek01.Service.Service
{
    /// <summary>
    /// 服务实现
    /// </summary>
    public class BaseService<T> : IBaseService<T> where T : class
    {
        /// <summary>
        /// 上下文
        /// </summary>
        private readonly UserDbContext db;
        /// <summary>
        /// 方法
        /// </summary>
        /// <param name="db">上下文</param>
        public BaseService(UserDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        ///添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响函数</returns>
        public int Add(T entity)
        {
            db.Add(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>返回受影响函数</returns>
        public int Delete(int id)
        {
            var entity = db.Set<T>().Find(id);
            db.Set<T>().Remove(entity);
            return db.SaveChanges();

        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <returns>列表</returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响函数</returns>
        public int Update(T entity)
        {
            db.Update(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>实体</returns>
        public T GetId(int id)
        {
            return db.Set<T>().Find(id);

        }
    }
}
